package rnd;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Logger;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.X509Certificate;

public class MNPLeads {

	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	private static final Logger log = Logger.getLogger(MNPLeads.class.getName());

	public static void main(String[] args) throws Exception {
		String apiUrl = "https://api.mynewplace.com/v1/5921339b/500861288920/lead";
		String email = "anbalimorrri8@gmail.com";
		String message = "";
		String firstName = "aj";
		String lastName = "morris";
		String phone = "0";

		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, 2013);
		c.set(Calendar.MONTH, 1);
		c.set(Calendar.DAY_OF_MONTH, 24);
		Date moveDate = c.getTime();

		System.out.println(call(apiUrl, email, moveDate, message, firstName, lastName, phone));
	}

	private static String call(String apiUrl, String email, Date moveDate,
			String message, String firstName, String lastName, String phone) {

		StringBuilder sb = new StringBuilder();
		if (isNotBlank(apiUrl) && isNotBlank(email)
				&& (null != moveDate)) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

				StringBuilder data = new StringBuilder();
				data.append("email").append("=").append(URLEncoder.encode(email, "UTF-8"));
				data.append("&").append("movedate").append("=").append(URLEncoder.encode(trimToEmpty(sdf.format(moveDate)), "UTF-8"));
				data.append("&").append("message").append("=").append(URLEncoder.encode(trimToEmpty(message), "UTF-8"));
				data.append("&").append("firstname").append("=").append(URLEncoder.encode(trimToEmpty(firstName), "UTF-8"));
				data.append("&").append("lastname").append("=").append(URLEncoder.encode(trimToEmpty(lastName), "UTF-8"));
				data.append("&").append("phoneno").append("=").append(URLEncoder.encode(trimToEmpty(phone), "UTF-8"));
				System.out.println(apiUrl + "?" + data);
				URL url = new URL(apiUrl);

				TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
					@Override
					public java.security.cert.X509Certificate[] getAcceptedIssuers() {
						return null;
					}

					public void checkClientTrusted(X509Certificate[] certs, String authType) {
						return;
					}

					public void checkServerTrusted(X509Certificate[] certs, String authType) {
						return;
					}

					@Override
					public void checkClientTrusted(
							java.security.cert.X509Certificate[] chain,
							String authType)
									throws java.security.cert.CertificateException {

					}

					@Override
					public void checkServerTrusted(
							java.security.cert.X509Certificate[] chain,
							String authType)
									throws java.security.cert.CertificateException {

					}

				}};


				SSLContext sc = SSLContext.getInstance("SSL");
				sc.init(null, trustAllCerts, new SecureRandom());

				HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
				conn.setDoOutput(true);
				conn.setDoInput(true);
				conn.setRequestMethod("POST");
				conn.setSSLSocketFactory(sc.getSocketFactory());
				conn.setAllowUserInteraction(false);
				OutputStreamWriter wr = new OutputStreamWriter(
						conn.getOutputStream());
				wr.write(data.toString());
				wr.flush();

				// Get the response
				BufferedReader rd;
				if (conn.getResponseCode() >= 400) {
					rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
				} else {
					rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				}

				String line;
				while ((line = rd.readLine()) != null) {
					sb.append(line);
				}
				wr.close();
				rd.close();
			} catch (UnsupportedEncodingException e) {
				sb.append("ERROR");
				e.printStackTrace(System.out);
			} catch (Exception e) {
				sb.append("ERROR");
				e.printStackTrace(System.out);
			}
		} else {
			sb.append("ERROR");
		}
		return sb.toString();
	}

	public static String trimToEmpty(String str) {
		return str == null ? "" : str.trim();
	}

    public static boolean isNotBlank(String str) {
        return !isBlank(str);
    }

    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }
}